package com.fingard.dsp.bank.directbank.gzdsf01;

import cfbs.api.CFBSConstant;
import cfbs.api.CFBSMsgUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsAPI;
import com.fingard.dsp.bank.directbank.gzdsf01.util.CfbsUtils;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import java.io.File;
import java.util.Date;

public class GZDSF01SinglePay extends GZDSF01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        if ("190802".equalsIgnoreCase(p_req1908.reqHeader.commandCode)) {
            return d_190802_SglPay(p_req1908);
        } else if ("190806".equalsIgnoreCase(p_req1908.reqHeader.commandCode)) {
            return d_190806_SglPay(p_req1908);
        } else {
            RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
            RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req1908);
            tmpRetDetail.respCode = "0";
            tmpRetDetail.respInfo = "未能识别的交易指令(CommandCode)：" + p_req1908.reqHeader.commandCode;
            tmpRetDetail.transState = PaymentState.FAIL_Payment;
            tmpRetDetail.payInfoCode = FailCode.E9981;
            retAts.writeRetDetail(tmpRetDetail);
            return retAts;
        }
    }

	public RetAtsSingle d_190802_SglPay(ReqSingle p_req1908) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req1908);

		try {
			StringBuilder tmpRealTimeSubmitRequest = new StringBuilder();
			tmpRealTimeSubmitRequest.append(GZDSF01TransCode.REALTIMEPAY);// 交易种类
			tmpRealTimeSubmitRequest.append("1202");// 报文类型
			tmpRealTimeSubmitRequest.append(String.format("%16s", p_req1908.singleDetail.askNumber).replace(" ", "0"));// 交易序号
			tmpRealTimeSubmitRequest.append(Format.Date8Format.format(p_req1908.singleDetail.getPayDateTime()));// 委托日期
			tmpRealTimeSubmitRequest.append(String.format("%8s", "").replace(" ", "0"));// 清算日期
			String payUserID = getBankConfig().getMapValueByKey("payUserIDMapping", p_req1908.singleDetail.payAct);
			tmpRealTimeSubmitRequest.append(String.format("%-18s", payUserID));// 用户编号
			tmpRealTimeSubmitRequest.append(String.format("%-12s", bankFront.org));// 发起方代码（收费机构代码）
			tmpRealTimeSubmitRequest.append(String.format("%-12s", ""));// 发起方分支代码
			tmpRealTimeSubmitRequest.append(String.format("%-12s", getBankConfig().getMapValueByKey("bankBranchMapping", p_req1908.singleDetail.payAct)));// 发起方开户行行号（收费机构开户行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-35s", p_req1908.singleDetail.payAct));// 发起方开户账号（收费机构开户账号）
			tmpRealTimeSubmitRequest.append(String.format("%-12s", convertBankCodeAreaMapping(p_req1908.singleDetail.recBankCode, p_req1908.singleDetail.recArea)));// 接收方代码（付款清算行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-12s", convertBankCodeAreaMapping(p_req1908.singleDetail.recBankCode, p_req1908.singleDetail.recArea)));// 接收方分支代码（付款人开户行行号）
			tmpRealTimeSubmitRequest.append(String.format("%-35s", p_req1908.singleDetail.recAct));// 收款人账号
			tmpRealTimeSubmitRequest.append(String.format(CfbsAPI.rightFill(p_req1908.singleDetail.recName, 60, " ")));// 收款人名称
			String businessTypes=getBankConfig().getValueAsString("businessTypes");
			if(StringHelper.isNullOrEmpty(businessTypes)) {
				businessTypes="00600";
			}
			tmpRealTimeSubmitRequest.append(businessTypes);// 业务种类
			String payContractNo = getBankConfig().getMapValueByKey("contractNoMapping", p_req1908.singleDetail.payAct);
			payContractNo = CFBSMsgUtil.rightFill(CFBSConstant.FILL_WORD_BLANK_SPACE, 60, payContractNo);
			tmpRealTimeSubmitRequest.append(String.format("%-60s", payContractNo));// 合同（协议）号
			String isPirvateFlag = "";
			if ("1".equals(p_req1908.singleDetail.isPrivate)) {
				isPirvateFlag = "S";
			} else {
				isPirvateFlag = "G";
			}
			tmpRealTimeSubmitRequest.append(isPirvateFlag);// 对公对私标识
			tmpRealTimeSubmitRequest.append(String.format("%-3s", convertCurToBank(p_req1908.singleDetail.recCur)));// 交易货币代码
			tmpRealTimeSubmitRequest.append(String.format("%15s", StringHelper.amountMultiply100(p_req1908.singleDetail.payAmount)).replace(" ", "0"));// 金额
			tmpRealTimeSubmitRequest.append(String.format("%15s", "").replace(" ", "0"));// 手续费
			tmpRealTimeSubmitRequest.append(String.format("%-60s", p_req1908.singleDetail.useType));// 附言
			tmpRealTimeSubmitRequest.append(String.format("%16s", "").replace(" ", "0"));// 业务处理方流水
			tmpRealTimeSubmitRequest.append(String.format("%-8s", ""));// 返回码
			tmpRealTimeSubmitRequest.append(String.format("%8s", "4").replace(" ", "0"));// 变长定制信息长度
			tmpRealTimeSubmitRequest.append(String.format("%8s", "1908").replace(" ", "0"));// 变长定制信息长度
			tmpRealTimeSubmitRequest.append(String.format("%-64s", ""));// 校验码
			
			WriteBankLogLn("实时代付请求报文生成摘要前明文数据:" + tmpRealTimeSubmitRequest.toString());
			
    		String tmpLoginRequest = new CfbsUtils(this.getSbLog()).txnEncSample(tmpRealTimeSubmitRequest.toString(), getEncryptKey(), getCharset());
    		
    		sendToBank(tmpLoginRequest);
    		
    		tmpRetDetail.respCode = "0"; 
			tmpRetDetail.respInfo = "交易已受理!";
			tmpRetDetail.transState = "I4001";
			tmpRetDetail.payInfoCode = "I4001";
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

    public RetAtsSingle d_190806_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail(p_req1908);

        try {
            StringBuilder tmpRealTimeSubmitRequest = new StringBuilder();
            tmpRealTimeSubmitRequest.append(GZDSF01TransCode.deal_1908_190806_300201);// 交易种类
            tmpRealTimeSubmitRequest.append("1202");// 报文类型
            tmpRealTimeSubmitRequest.append(String.format("%16s", p_req1908.singleDetail.askNumber).replace(" ", "0"));// 交易序号
            tmpRealTimeSubmitRequest.append(Format.Date8Format.format(p_req1908.singleDetail.getPayDateTime()));// 委托日期
            tmpRealTimeSubmitRequest.append(String.format("%8s", "").replace(" ", "0"));// 清算日期
            tmpRealTimeSubmitRequest.append(String.format("%-12s", bankFront.org));// 发起方代码（收费机构代码）
            tmpRealTimeSubmitRequest.append(String.format("%-12s", ""));// 发起方分支代码
            tmpRealTimeSubmitRequest.append(String.format("%-12s", convertBankCodeAreaMapping(p_req1908.singleDetail.recBankCode, p_req1908.singleDetail.recArea)));// 接收方代码（付款清算行行号）
            tmpRealTimeSubmitRequest.append(String.format("%-12s", ""));// 接收方分支代码（付款人开户行行号）
            tmpRealTimeSubmitRequest.append(String.format("%-18s", p_req1908.singleDetail.recAct));// 原数据元
            tmpRealTimeSubmitRequest.append(String.format("%16s", "").replace(" ", "0"));// 业务处理方流水
            tmpRealTimeSubmitRequest.append(String.format("%-8s", ""));// 返回码
            tmpRealTimeSubmitRequest.append(String.format("%8s", "4").replace(" ", "0"));// 变长定制信息长度
            tmpRealTimeSubmitRequest.append(String.format("%8s", "1908").replace(" ", "0"));// 变长定制信息长度
            tmpRealTimeSubmitRequest.append(String.format("%-64s", ""));// 校验码

            WriteBankLogLn("实时代收冲正请求报文生成摘要前明文数据:" + tmpRealTimeSubmitRequest.toString());

            String tmpLoginRequest = new CfbsUtils(this.getSbLog()).txnEncSample(tmpRealTimeSubmitRequest.toString(), getEncryptKey(), getCharset());

            sendToBank(tmpLoginRequest);

            tmpRetDetail.respCode = "0";
            tmpRetDetail.respInfo = "交易已受理!";
            tmpRetDetail.transState = "I4001";
            tmpRetDetail.payInfoCode = "I4001";
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

	@Override
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req1944.askNumber;
		
		try {
    	    File file = new File(getTempFileDirectory(p_req1944.getBgnDateTime()) + File.separator + "REALTIMEPAY" + File.separator + p_req1944.askNumber + ".txt");
    		WriteBankLogLn("本地单笔代付查询结果文件路径:" + file.getAbsolutePath());
    		int index = 0;
    		while(true) {
    			++index;
    			Thread.sleep(1000);
    			System.out.println("第" + index + "秒后遍历单笔代付查询结果文件是否存在:" + file.exists());
    			if (file.exists() || (index>500)) {
    				break;
    			}
    		}
    		if (file.exists()) {
				String tmpStrRet = FileHelper.readToString(file, getCharset());
				WriteBankLogLn("单笔代付/实时代收冲正 查询收到通知响应数据:\r\n" + tmpStrRet);
				StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet, tmpSbMsg);
                if (tmpBkReader != null) {
                	if (tmpBkReader.read("/ATSYH/TransResp/TransParam/DetailRecord")) {
                		tmpRetDetail.respCode = tmpBkReader.readedXElement.getSingleText("RespCode");
                		tmpRetDetail.respInfo = tmpBkReader.readedXElement.getSingleText("RespInfo");
                		tmpRetDetail.transState = tmpBkReader.readedXElement.getSingleText("TransState");
                		tmpRetDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("PayInfoCode");
                	}
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
			} else {
				tmpRetDetail.respCode = "-1";
        		tmpRetDetail.respInfo = "记录不存在!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
